package com.xudow.app.ui;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.activeshare.edu.ucenter.models.cart.CartItem;
import com.activeshare.edu.ucenter.models.cart.ShoppingCartWithCourse;
import com.activeshare.edu.ucenter.models.course.CourseWithOtherInfo;
import com.xudow.app.R;
import com.xudow.app.model.CartModle;
import com.xudow.app.model.Coures;
import com.xudow.app.newui.bean.LsCatMessage;
import com.xudow.app.ui.adapter.CartListAdapter;
import com.xudow.app.ui.task.CartItemDeletTask;
import com.xudow.app.ui.task.CartItemsMakeOrderTask;
import com.xudow.app.ui.task.GetCarListTask;
import com.xudow.app.ui.user.OrdersActivity;
import com.xudow.app.util.Maps;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

public class CartActivity extends BaseActivity implements View.OnClickListener,
        CartListAdapter.AdapterCallBack,DialogInterface.OnClickListener {
    private TextView editCart;
    private TextView paybnt;
    private TextView totalPrice;
    private TextView cart_num_ed;//编辑时删除按钮
    private ImageView selectAll;
    private ExpandableListView cartList;
    private GetCarListTask getCarListTask;
    private List<LsCatMessage.CartItemsEntity> list;//购物车数据

    @Override
    public void isAllselect() {
        boolean allselect=true;
        for (LsCatMessage.CartItemsEntity cm: list) {
                if (!cm.isSelect){
                    allselect=false;
                    break;
                }
            for (LsCatMessage.CartItemsEntity.ListEntity cou: cm.getList()) {
                if(!cou.isSelect){
                    allselect=false;
                    break;
                }
            }
        }
        if (allselect)
            selectAll.setImageResource(R.mipmap.btn_cart_checked);
        else
            selectAll.setImageResource(R.mipmap.btn_cart_unchecked);
    }

    private CartListAdapter adapter;
    private boolean selectAll_Flage=false;//全选标记
    private boolean edFlag=false;//标记标记
    String TAG="CartActivity";
    int flage=1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cart);
        initview();

    }

    @Override
    protected void onStart() {
        super.onStart();
        initData();
        initListener();

    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.e(TAG, "onRestart: ");
        initData();
        adapter.notifyDataSetChanged();
    }

    /**
     * 初始化网络数据
     */
    private void initData() {

        getCarListTask=new GetCarListTask(getApplicationContext(),getCartHandler);
        addTask(getCarListTask);
        getCarListTask.execute();
        showLodingDialog("正在获取");
    }

    private Handler getCartHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            hideLoadingDialog();
            if (msg.what==getCarListTask.SUCCESS){
                list=null;
                list=(ArrayList<LsCatMessage.CartItemsEntity>)msg.obj;
                if (null==list){
                    Log.e(TAG, "cartList为空: " + (list == null));
                    return;
                }
                adapter.setData(list);
                //默认展开
                double price=0;
                for (int i=0;i<list.size();i++){
                    cartList.expandGroup(i);
                    LsCatMessage.CartItemsEntity m=list.get(i);
                    List<LsCatMessage.CartItemsEntity.ListEntity> cl=m.getList();
                    for (LsCatMessage.CartItemsEntity.ListEntity c:cl) {
                        if (c.isSelect){
                            price=price+c.getCourseWithOtherInfo().getActualPrice();
                        }
                    }
                }
                totalPrice.setText(price+"0");
            }else
                getMyApp().makeToast(msg.getData().getString("errMessage"));
        }
    };
    LinearLayout cart_check_all_btn;
    private void initview() {
         editCart=(TextView)findViewById(R.id.cart_edit_btn);
         paybnt=(TextView)findViewById(R.id.cart_pay_btn);
        totalPrice=(TextView)findViewById(R.id.cart_total_price);
        selectAll=(ImageView)findViewById(R.id.cart_check_all_img);
        cartList=(ExpandableListView)findViewById(R.id.cart_exList_view);
        cart_num_ed=(TextView)findViewById(R.id.cart_check_num);
        cart_check_all_btn=(LinearLayout)findViewById(R.id.cart_check_all_btn);
        cart_check_all_btn.setOnClickListener(this);
        cartList.setGroupIndicator(null);//去掉group默认标签
        adapter=new CartListAdapter(this,null);
        cartList.setAdapter(adapter);
        adapter.setCallback(this);
        adapter.setCallback(this);
    }

    public void goBackClick(View view){
        finish();
    }

    /**
     * 删除选中课程
     */
    public void doDeletTask(){
        HashMap<String,String> pramers= Maps.newHashMap();
        getItems(pramers);
        CartItemDeletTask deletTask=new CartItemDeletTask(getApplicationContext(),deletHandler);
        addTask(deletTask);
        deletTask.execute(pramers);
        showLodingDialog("正在处理");
    }

    /**
     * 获取选中的item
     */
    private void getItems(HashMap<String,String> hashMap) {
        StringBuffer sb=new StringBuffer();
        for (LsCatMessage.CartItemsEntity cm: list) {
            for (LsCatMessage.CartItemsEntity.ListEntity cou: cm.getList()) {
                if(cou.isSelect){
                    sb.append(cou.getId());
                    sb.append(",");
                }
            }
        }
        sb.deleteCharAt(sb.length() - 1);
        Log.e(TAG, "getItems: " + sb.toString());
        hashMap.put("item_id", sb.toString());
    }

    /**
     * 结算购物车参数组合
     * @param hashMap
     */
    /*private void getcartItems(HashMap<String,String> hashMap) {
        StringBuffer sb=new StringBuffer();
        for (CartModle cm: list) {
            for (Coures cou: cm.couresList) {
                if(cou.isSelect){
                    sb.append(cm.itemId);
                    sb.append(",");
                }
            }
        }
        sb.deleteCharAt(sb.length()-1);
        Log.e(TAG, "getcarItems: "+sb.toString());
        hashMap.put("cartId", sb.toString());
    }*/
    /**
     * 删除购物车课程Handler
     */
    private Handler deletHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            hideLoadingDialog();
            if (msg.what== CartItemDeletTask.SUCCESS){
                getMyApp().makeToast("删除成功");
                //TODO list数据删除
                //removeSelect();
                initData();
            }else
                getMyApp().makeToast("删除失败");
        }
    };
    private int getSelectCount(){
        int n=0;
        for (LsCatMessage.CartItemsEntity cm: list) {
            for (LsCatMessage.CartItemsEntity.ListEntity cour:cm.getList()) {
                if (cour.isSelect){
                    n++;
                }
            }
        }
        return n;
    }

    private void initListener() {
        editCart.setOnClickListener(this);
        paybnt.setOnClickListener(this);
        selectAll.setOnClickListener(this);
        cart_num_ed.setOnClickListener(this);
        //group点击不收缩
        cartList.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView expandableListView, View view, int i, long l) {
                return true;
            }
        });

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.cart_edit_btn:
                edFlag=!edFlag;
                if (edFlag){
                    editCart.setText("完成");
                    editCart.setTextColor(Color.RED);
                    totalPrice.setVisibility(View.GONE);
                    paybnt.setVisibility(View.GONE);
                    cart_num_ed.setVisibility(View.VISIBLE);
                }else{
                    editCart.setText("编辑");
                    editCart.setTextColor(Color.BLACK);
                    totalPrice.setVisibility(View.VISIBLE);
                    paybnt.setVisibility(View.VISIBLE);
                    cart_num_ed.setVisibility(View.GONE);
                }
                adapter.setEdFlag(edFlag);
                break;
            case R.id.cart_pay_btn:
                if(getSelectCount()==0){
                    getMyApp().makeToast("未选结算课程");
                    return;
                }
                dialog("请在30分钟内付款，否则订单会自动取消，同时学兜50元优惠将视为已使用。请谨慎下单。",1);
                break;
            case R.id.cart_check_num:
                getMyApp().makeToast("点击删除");
                doDeletTask();
                break;
            case R.id.cart_check_all_btn:
                selectAll_Flage=!selectAll_Flage;
                if(selectAll_Flage){
                    selectAll.setImageResource(R.mipmap.btn_cart_checked);
                    changeListData(true);
                }else {
                    changeListData(false);
                    selectAll.setImageResource(R.mipmap.btn_cart_unchecked);
                }
                getCouresPrice();
                break;
        }
    }
    /**
     * 对话框
     */
    protected void dialog(String title,int n) {
        flage=n;
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(title);  builder.setTitle("提示");
        builder.setPositiveButton("确认", CartActivity.this);
        builder.setNegativeButton("取消", CartActivity.this);
        builder.create().show();
    }
    /**
     * 结算购物车
     */
    private void doMakeorders() {
        HashMap<String,String> pramers=new HashMap<String, String>();
        getItems(pramers);
        CartItemsMakeOrderTask task=new CartItemsMakeOrderTask(getApplicationContext(),makeHandler);
        addTask(task);
        task.execute(pramers);
        showLodingDialog("正在生成订单");
    }
    private Handler makeHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            hideLoadingDialog();
            if (msg.what==CartItemsMakeOrderTask.SUCCESS){
                //TODO 跳转未支付订单列表
               // removeSelect();
                Intent intent=new Intent(getApplicationContext(), OrdersActivity.class);
                intent.putExtra("orderstate",2);
                startActivity(intent);

            }else {
                String str=msg.obj.toString();
                if (null==str){
                    str="生成订单失败";
                }
                getMyApp().makeToast(str);
            }
        }
    };

    private void changeListData(boolean b) {
        for (LsCatMessage.CartItemsEntity cm:list) {
            cm.isSelect=b;
            for (LsCatMessage.CartItemsEntity.ListEntity coures:cm.getList()) {
                coures.isSelect=b;
            }
        }
        adapter.notifyDataSetChanged();
    }

    @Override
    public void getCouresPrice() {
        double price=0;
        for (int i=0;i<list.size();i++){
            LsCatMessage.CartItemsEntity m=list.get(i);
            List<LsCatMessage.CartItemsEntity.ListEntity> cl=m.getList();
            for (LsCatMessage.CartItemsEntity.ListEntity c:cl) {
                if (c.isSelect){
                    price=price+c.getCourseWithOtherInfo().getActualPrice();
                }
            }
        }
        totalPrice.setText("¥"+price+"0");
    }

    @Override
    public void onClick(DialogInterface dialog, int which) {
        if (-1 == which) {
                doMakeorders();
        }
            dialog.dismiss();

    }
}
